package com.devunion.salon.client.app.mvc.view;

import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.data.*;
import com.extjs.gxt.ui.client.widget.*;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.grid.*;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Events;
import com.extjs.gxt.ui.client.event.*;
import com.devunion.salon.client.app.mvc.SalonEvents;
import com.devunion.salon.client.app.bean.search.ProductSearchPagingLoadConfig;
import com.devunion.salon.client.app.bean.VendorModel;
import com.devunion.salon.client.rpc.VendorService;
import com.devunion.salon.client.rpc.VendorServiceAsync;
import com.devunion.salon.client.Constants;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.Window;

import java.util.List;
import java.util.ArrayList;


/**
 * Created by IntelliJ IDEA.
 * User: Andrei
 * Date: 07.03.2009
 * Time: 23:55:39
 * To change this template use File | Settings | File Templates.
 */
public class VendorView extends View {

    Grid<VendorModel> grid;

    public VendorView (Controller controller) {
        super(controller);
    }

    protected void handleEvent(AppEvent<?> event) {
           switch (event.type) {
               case SalonEvents.COMPONENT_INIT:
                   initComponent();
                   break;
           }
       }

      private void initComponent() {
        RpcProxy proxy = new RpcProxy() {
            @Override
            public void load(Object loadConfig, AsyncCallback callback) {
                VendorService.App.getInstance().findVendors((BasePagingLoadConfig) loadConfig, callback);
            }
        };

          // loader
                BasePagingLoader loader = new BasePagingLoader(proxy);
                final ProductSearchPagingLoadConfig searchPagingLoadConfig = new ProductSearchPagingLoadConfig();
                loader.useLoadConfig(searchPagingLoadConfig);
                loader.setRemoteSort(true);

                final PagingToolBar toolBar = new PagingToolBar(15);
                toolBar.bind(loader);

                loader.load(0, 15);

                final ListStore<VendorModel> store = new ListStore<VendorModel>(loader);
                List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
                ColumnConfig config = new ColumnConfig("edit", "", 40);
                config.setRenderer(new GridCellRenderer() {
                    public String render(ModelData modelData, String s, ColumnData columnData, int i, int i1, ListStore listStore) {
                        return "<img src='tempimg/edit.png' title='Edit' />";
                    }
                });

                columns.add(config);
                columns.add(new ColumnConfig("code", "Code", 150));
                columns.add(new ColumnConfig("address", "Address", 100));

                ColumnModel cm = new ColumnModel(columns);

                grid = new Grid<VendorModel>(store, cm);
                grid.setLoadMask(true);
                grid.setAutoWidth(true);
                grid.setBorders(true);
                grid.setAutoExpandColumn("code");

                grid.addListener(Events.CellClick, new Listener<GridEvent>() {
                    public void handleEvent(GridEvent gridEvent) {
                        VendorModel model = store.getAt(gridEvent.rowIndex);
                        createDialog(model.getCode(), model.getAddress(), gridEvent.rowIndex);
                    }
                });


                ContentPanel centerPanel = Registry.get(Constants.APP_CENTER_PANEL);
                centerPanel.removeAll();
                //centerPanel.setHeading("Products List");
                centerPanel.setLayout(new FitLayout());
                VerticalPanel vp = new VerticalPanel();
                grid.setAutoHeight(true);



                vp.add(grid);
                vp.add(toolBar);
                vp.setAutoHeight(true);
                centerPanel.add(vp);
                centerPanel.layout();

      }

    private void save(final Object originalCode, final Object code, final Object address, final int index, final Dialog dialog) {
        VendorServiceAsync serviceAsync = VendorService.App.getInstance();
        serviceAsync.updateVendor((String)originalCode, (String)code, (String)address, new AsyncCallback() {
            public void onFailure(Throwable throwable) {
                Window.alert("Cannot update. Caused by " + throwable);
            }

            public void onSuccess(Object o) {
                ListStore<VendorModel> listStore = grid.getStore();
                VendorModel vendorModel = listStore.getAt(index);
                vendorModel.setCode((String)code);
                vendorModel.setAddress((String)address);
                grid.getStore().commitChanges();
                grid.getStore().update(vendorModel);
                dialog.hide();
            }
        });
    }

    private void createDialog(final String code, String address, final int index) {
        final Dialog dialog = new Dialog();
        BorderLayout layout = new BorderLayout();
        dialog.setLayout(layout);
        dialog.setFooter(false);
        dialog.getButtonBar().removeAll();
        FormPanel formPanel = new FormPanel();
        final TextField codeField = new TextField();
        codeField.setFieldLabel("Code");
        codeField.setAllowBlank(false);
        codeField.setValue(code);
        final TextField addressField = new TextField();
        addressField.setFieldLabel("Address");
        addressField.setAllowBlank(true);
        addressField.setValue(address);
        formPanel.add(codeField);
        formPanel.add(addressField);
        formPanel.setAutoWidth(true);
        formPanel.setAutoHeight(true);
        dialog.setAutoWidth(true);
        dialog.setModal(true);
        Button saveButton = new Button("Save");
        saveButton.addListener(Events.OnClick, new Listener<BaseEvent>() {
            public void handleEvent(BaseEvent baseEvent) {
                  save(code, codeField.getValue(), addressField.getValue(), index, dialog);
            }
        });

       formPanel.add(saveButton);
       dialog.add(formPanel);
       dialog.show();

    }


}
